package com.lp.rpc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.List;

public class LpServer {

    /**
     * 这里加入了线程池，让任务交给executorGroup线程池中的线程取执行，因为如果没有使用executorGroup，那么任务是交给workGroup线程池去执行
     * 如果遇到耗时任务，还有并发大，那么workGroup线程将不能即时处理。
     *
     */
    private static final EventExecutorGroup executorGroup =
            new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 4);

    public void startServer(int serverPort){
        //bossGroup和workGroup线程数默认都为cpu核数的两倍
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 4);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .localAddress(serverPort)
                    .childHandler(new LpServerChannelInitializer(executorGroup));
            ChannelFuture future = serverBootstrap.bind(serverPort).sync();
            future.channel().closeFuture().sync();
        }catch (InterruptedException e){
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
